package com.zc.im.service.customer.impl;

import com.zc.im.mapper.customer.ZcCustomerServiceMapper;
import com.zc.im.mapper.customer.ZcCustomerServiceRelationMapper;
import com.zc.im.mapper.user.ZcUserMapper;
import com.zc.im.model.customer.*;
import com.zc.im.model.user.ZcAdminUser;
import com.zc.im.model.user.ZcUser;
import com.zc.im.model.user.ZcUserKey;
import com.zc.im.service.customer.CustomerService;
import com.zc.im.service.user.ZcAdminUseService;
import com.zc.im.util.ImGolbalTypeContext;
import com.zc.im.util.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangcc on 2017/7/9.
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(CustomerServiceImpl.class);

    @Autowired
    private ZcCustomerServiceMapper zcCustomerServiceMapper;

    @Autowired
    private ZcCustomerServiceRelationMapper zcCustomerServiceRelationMapper;

    @Autowired
    private ZcUserMapper userMapper;

    @Autowired
    private ZcAdminUseService zcAdminUseService;

    /**
     * 添加服务
     * @param zcCustomerServiceModel
     * @return
     */
    @Override
    public Integer insertCustomerService(ZcCustomerService zcCustomerServiceModel) {
        Integer customerService = null;
        if (zcCustomerServiceModel == null) {
            logger.info("Insert CustomerService is null");
        }
        zcCustomerServiceModel.setCreatedTime(new Date());
        zcCustomerServiceModel.setStatus(ImGolbalTypeContext.STATUS_VALID);
        try {
            customerService = zcCustomerServiceMapper.insertSelective(zcCustomerServiceModel);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return customerService;
    }

    /**
     *删除服务客服
     * @param id
     * @return
     */
    @Override
    public Integer deleteCustomerService(Integer id) {
        Integer customerServiceId = null;
        if (id == null) {
            logger.info("delete CustomerService is null");
            return customerServiceId;
        }
        try {
            ZcCustomerServiceKey serviceKey = new ZcCustomerServiceKey();
            serviceKey.setId(id);
            customerServiceId = zcCustomerServiceMapper.deleteByPrimaryKey(serviceKey);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return customerServiceId;
    }


    /**
     * 删除客服绑定通过uid
     * @param uid
     * @return
     */
    @Override
    public Integer deleteCustomerServiceUid(Integer uid) {
        Integer customerServiceUid = null;
        if (uid==null) {
            return customerServiceUid;
        }
        ZcCustomerServiceExample example = new  ZcCustomerServiceExample();
        ZcCustomerServiceExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(uid);
        try {
            customerServiceUid =  zcCustomerServiceMapper.deleteByExample(example);
        }catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return customerServiceUid;
    }

    /**
     * 更新服务客服
     * @param zcCustomerService
     * @return
     */
    @Override
    public Integer updateCustomerService(ZcCustomerService zcCustomerService) {
        Integer customerServiceId = null;
        if (zcCustomerService == null) {
            logger.info("Update CustomerService is null");
            return customerServiceId;
        }
        zcCustomerService.setUpdatedTime(new Date());
        try {
            ZcCustomerServiceExample example = new ZcCustomerServiceExample();
            ZcCustomerServiceExample.Criteria criteria = example.createCriteria();
            criteria.andIdEqualTo(zcCustomerService.getId());
            customerServiceId = zcCustomerServiceMapper.updateByExampleSelective(zcCustomerService, example);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return customerServiceId;
    }

    @Override
    public ZcCustomerService  findCustomerService(String custcomerServiceType) {
        ZcCustomerService zcCustomerService = null;
        if (StringUtils.isEmpty(custcomerServiceType)) {
            logger.info("QuerAll CustomeService is null");
            return zcCustomerService;
        }
        try {
            ZcCustomerServiceExample serviceExample = new ZcCustomerServiceExample();
            ZcCustomerServiceExample.Criteria criteria =  serviceExample.createCriteria();
            criteria.andCustomerServiceTypeEqualTo(custcomerServiceType);
            List<ZcCustomerService> customerServices = zcCustomerServiceMapper.selectByExample(serviceExample);
            if(customerServices == null || customerServices.size() == 0){
                return  zcCustomerService;
            }
            zcCustomerService = customerServices.get(0);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return zcCustomerService;
    }


    /**
     *取出最少客服
     * @return
     */
    public ZcCustomerService findLeastCustomerService(ZcCustomerService zcCustomerService) {
        ZcCustomerService LeastCustomerService = null;
        if (zcCustomerService == null) {
            return zcCustomerService;
        }
        ZcCustomerServiceExample example = new ZcCustomerServiceExample();
        ZcCustomerServiceExample.Criteria criteria =  example.createCriteria();
        criteria.andCustomerServiceTypeEqualTo(zcCustomerService.getCustomerServiceType());
        example.setOrderByClause("service_user_num");
        try {
            List<ZcCustomerService> ListLeastCustomerService = zcCustomerServiceMapper.selectByExample(example);
            if (ListLeastCustomerService == null || ListLeastCustomerService.size()==0) {
                return    LeastCustomerService;
            }
            LeastCustomerService = ListLeastCustomerService.get(0);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return LeastCustomerService;
    }



    public Map<String, ZcAdminUser> queryOrSaveUserRelationCustomerService(Integer userId){
        Map<String, ZcAdminUser> infoMap = new HashMap<>();
        if(userId == null){
            return infoMap;
        }
        //通过用户ID查询用户信息
        ZcUser zcUser = findUserById(userId);
        if(zcUser == null){
            logger.error("当前用户不存在 userId:{}", userId);
        }

        ZcAdminUser zcAdminUser = null;
        //通过用户ID查询客服关联
        ZcCustomerServiceRelation relation = findRelationByUserAndType(zcUser.getType().intValue(), userId);
        if(relation == null){
            logger.error("客服关联数据为空,新建客服关联数据");
            ZcCustomerService service = findCustomerServiceForMinNum(zcUser.getType().intValue());
            if(service == null){
                logger.error("没有匹配的客服信息");
                return infoMap;
            }
            //添加关联
            ZcCustomerServiceRelation serviceRelation = insertServiceRelation(zcUser, service);
            //查询客服信息
            zcAdminUser = findAdminUserId(serviceRelation.getCustomerServiceUserId());
            //更新客服服务数量
            updateCustomerServiceNum(service);
        }else{
            //查询客服信息
            zcAdminUser = findAdminUserId(relation.getCustomerServiceUserId());
        }
        infoMap.put(ImGolbalTypeContext.IM_CUSTOMER_SERVICE_INFO, zcAdminUser);
        return infoMap;
    }



    /**
     * 查询客服信息
     * @return
     */
    public ZcAdminUser findAdminUserId(Integer adminUserId) {
        ZcAdminUser zcAdminUser = new ZcAdminUser();
        if (adminUserId==null) {
            logger.error("find adminUserId is null");
            return zcAdminUser;
        }
        try {
            zcAdminUser  =  zcAdminUseService.findZcAdminUser(adminUserId) ;
        }catch (Exception e) {
            logger.error(e.getMessage() , e);
        }
        return zcAdminUser;


 }

    /**
     * 查询用户信息
     * @param userId
     * @return
     */
    public ZcUser findUserById(Integer userId){
        ZcUser zcUser = null;
        //通过用户ID查询用户信息
        if(userId == null){
            return zcUser;
        }
        ZcUserKey key = new ZcUserKey();
        key.setUid(userId);
        zcUser = userMapper.selectByPrimaryKey(key);
        return zcUser;
    }


    /**
     * 查询客服绑定的用户按类型和用户ID
     * 2017-7-11 18:49:55
     * @param type
     * @param userId
     * @return
     */
    public ZcCustomerServiceRelation findRelationByUserAndType(Integer type, Integer userId){
        ZcCustomerServiceRelation relation = null;
        ZcCustomerServiceRelationExample relationExample = new ZcCustomerServiceRelationExample();
        ZcCustomerServiceRelationExample.Criteria criteria = relationExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        if(ImGolbalTypeContext.IM_PERSONAL == type){
            criteria.andCustomerServiceTypeEqualTo(ImGolbalTypeContext.IM_GROUP_TYPE_PEOPLE);
        }
        if(ImGolbalTypeContext.IM_ENTERPRISE == type){
            criteria.andCustomerServiceTypeEqualTo(ImGolbalTypeContext.IM_GROUP_TYPE_COMPANY);
        }
        if(userId!= null){
            criteria.andUserIdEqualTo(userId);
        }
        List<ZcCustomerServiceRelation> serviceRelations = zcCustomerServiceRelationMapper.selectByExample(relationExample);
        if(serviceRelations == null || serviceRelations.size() == 0){
            return relation;
        }
        relation = serviceRelations.get(0);
        return relation;
    }

    /**
     * 查询服务最少的客服
     * 2017-7-11 19:06:33
     * @param userType
     * @return
     */
    public ZcCustomerService findCustomerServiceForMinNum(Integer userType){
        ZcCustomerService service = null;
        if(userType == null){
            return service;
        }
        service = new ZcCustomerService();
        service.setCustomerServiceType(setRelationType(userType));
        ZcCustomerService zcCustomerService =  findLeastCustomerService(service);
        //ZcCustomerService zcCustomerService = zcCustomerServiceMapper.findCustomerServiceForMinNum(service);
        return zcCustomerService;
    }

    /**
     * 添加客服关联
     * 2017-7-11 19:13:55
     * @param zcUser
     * @param customerService
     * @return
     */
    public ZcCustomerServiceRelation insertServiceRelation(ZcUser zcUser, ZcCustomerService customerService){
        ZcCustomerServiceRelation relation = null;
        if(customerService == null){
            return relation;
        }
        relation = new ZcCustomerServiceRelation();
        relation.setUserId(zcUser.getUid());
        relation.setCustomerServiceUserId(customerService.getUserId());
        relation.setCustomerServiceType(setRelationType(zcUser.getType().intValue()));
        relation.setCreatedTime(new Date());
        relation.setStatus(ImGolbalTypeContext.STATUS_VALID);
        zcCustomerServiceRelationMapper.insertSelective(relation);
        relation.setId(relation.getId());
        return relation;
    }


    public String setRelationType(Integer userType){
        String customerUserType = null;
        if(ImGolbalTypeContext.IM_PERSONAL == userType){
            customerUserType = ImGolbalTypeContext.IM_GROUP_TYPE_PEOPLE;
        }
        if(ImGolbalTypeContext.IM_ENTERPRISE == userType){
            customerUserType = ImGolbalTypeContext.IM_GROUP_TYPE_COMPANY;
        }
        return customerUserType;
    }


    /**
     * 更新客服服务数量
     * 2017-7-11 19:28:59
     * @param service
     * @return
     */
    public Integer updateCustomerServiceNum(ZcCustomerService service){
        Integer updateStatus = 0;
        if(service == null){
            return updateStatus;
        }
        Integer serviceUserNum = service.getServiceUserNum() + 1;
        service.setServiceUserNum(serviceUserNum);
        service.setId(service.getId());
        updateStatus = updateCustomerService(service);
        return updateStatus;
    }


}
